package com.autumn.platform.core.crypto;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;

public class RSAUtils extends CryptoUtils {

    /**
     * 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * 签名算法
     */
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";//SHA1WithRSA

    /**
     * 生成RSA密钥对
     */
    public static RsaKeyPair getRsaKeyPair() {
        try {
            KeyPairGenerator keyPairGen = null;
            Provider provider = getProvider();
            if (null == provider) {
                keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            } else {
                keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM, provider);
            }
            keyPairGen.initialize(1024, random);
            KeyPair keyPair = keyPairGen.generateKeyPair();
            String privateKey = encodeToString(keyPair.getPrivate().getEncoded());
            String publicKey = encodeToString(keyPair.getPublic().getEncoded());
            return new RsaKeyPair(publicKey, privateKey);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取公钥
     * 
     * @param publicKey
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) {
        try {
            byte[] bytes = decodeFromString(publicKey);
            X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(bytes);
            PublicKey pk = getKeyFactory().generatePublic(x509KeySpec);
            return pk;
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取私钥
     * 
     * @param privateKey
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) {
        try {
            byte[] bytes = decodeFromString(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(bytes);
            PrivateKey pk = getKeyFactory().generatePrivate(pkcs8KeySpec);
            return pk;
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 用私钥对信息生成数字签名
     * 
     * @param data 已加密数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     */
    public static String sign(byte[] data, String privateKey) {
        try {
            PrivateKey privateK = getPrivateKey(privateKey);
            Signature signature = getSignature();
            signature.initSign(privateK);
            signature.update(data);
            return encodeToString(signature.sign());
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (SignatureException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 校验数字签名
     * 
     * @param data 已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @param sign 数字签名
     * @return
     */
    public static boolean verify(byte[] data, String publicKey, String sign) {
        try {
            PublicKey publicK = getPublicKey(publicKey);
            Signature signature = getSignature();
            signature.initVerify(publicK);
            signature.update(data);
            return signature.verify(decodeFromString(sign));
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (SignatureException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 公钥加密
     * 
     * @param plainText
     * @param publicKey
     * @return
     */
    public static String encryptByPublicKey(String plainText, String publicKey) {
        Cipher cipher = getCipher(true, publicKey, true);
        byte[] src = plainText.getBytes();
        byte[] datas = cipherData(cipher, src, 117);
        return encodeToString(datas);
    }

    /**
     * 私钥加密
     * 
     * @param plainText
     * @param privateKey
     * @return
     */
    public static String encryptByPrivateKey(String plainText, String privateKey) {
        Cipher cipher = getCipher(true, privateKey, false);
        byte[] src = plainText.getBytes();
        byte[] datas = cipherData(cipher, src, 117);
        return encodeToString(datas);
    }

    /**
     * 公钥解密
     * 
     * @param plainText
     * @param publicKey
     * @return
     */
    public static String decryptByPublicKey(String encryptText, String publicKey) {
        Cipher cipher = getCipher(false, publicKey, true);
        byte[] src = decodeFromString(encryptText);
        byte[] datas = cipherData(cipher, src, 128);
        return new String(datas);
    }

    /**
     * 私钥解密
     * 
     * @param encryptText
     * @param privateKey
     * @return
     */
    public static String decryptByPrivateKey(String encryptText, String privateKey) {
        Cipher cipher = getCipher(false, privateKey, false);
        byte[] src = decodeFromString(encryptText);
        byte[] datas = cipherData(cipher, src, 128);
        return new String(datas);
    }

    /**
     * 获取KeyFactory对象
     * 
     * @return
     */
    private static KeyFactory getKeyFactory() {
        try {
            Provider provider = getProvider();
            if (null == provider) {
                return KeyFactory.getInstance(KEY_ALGORITHM);
            } else {
                return KeyFactory.getInstance(KEY_ALGORITHM, provider);
            }
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取Signature对象
     * 
     * @return
     */
    private static Signature getSignature() {
        try {
            Provider provider = getProvider();
            if (null == provider) {
                return Signature.getInstance(SIGNATURE_ALGORITHM);
            } else {
                return Signature.getInstance(SIGNATURE_ALGORITHM, provider);
            }
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取Cipher对象
     * 
     * @param encode
     * @param keyString
     * @param isPublicKey
     * @return
     */
    private static Cipher getCipher(boolean encode, String keyString, boolean isPublicKey) {
        try {
            Key key = isPublicKey ? getPublicKey(keyString) : getPrivateKey(keyString);
            Cipher cipher = getCipher(KEY_ALGORITHM);
            cipher.init(encode ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, key);
            return cipher;
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加解密数据
     * 
     * @param cipher
     * @param src
     * @param blockSize
     * @return
     */
    private static byte[] cipherData(Cipher cipher, byte[] src, int blockSize) {
        ByteArrayOutputStream out = null;
        try {
            int inputLen = src.length;
            out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] cache;
            int i = 0;
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > blockSize) {
                    cache = cipher.doFinal(src, offSet, blockSize);
                } else {
                    cache = cipher.doFinal(src, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * blockSize;
            }
            return out.toByteArray();
        } catch (IllegalBlockSizeException e) {
            throw new RuntimeException(e);
        } catch (BadPaddingException e) {
            throw new RuntimeException(e);
        } finally {
            if (null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * RSA密钥对象
     */
    public static class RsaKeyPair implements Serializable {

        private static final long serialVersionUID = 2130689702406754025L;

        /**
         * 公钥
         */
        private String publicKey;

        /**
         * 私钥
         */
        private String privateKey;

        public RsaKeyPair() {}

        public RsaKeyPair(String publicKey, String privateKey) {
            this.publicKey = publicKey;
            this.privateKey = privateKey;
        }

        public String getPublicKey() {
            return publicKey;
        }

        public void setPublicKey(String publicKey) {
            this.publicKey = publicKey;
        }

        public String getPrivateKey() {
            return privateKey;
        }

        public void setPrivateKey(String privateKey) {
            this.privateKey = privateKey;
        }
    }
}
